package com.yc.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.sun.media.jfxmedia.logging.Logger;
import com.yc.QueryResult;
import com.yc.R_Code;
import com.yc.Result;
import com.yc.entities.*;
import com.yc.entities.custom.AppHomePageUserBean;
import com.yc.entities.custom.CustomIndexQueryResponseBean;
import com.yc.service.*;
import com.yc.utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 用户主体账户信息表 前端控制器
 * </p>
 *
 * @author kuakha
 * @since 2021-04-07
 */
@RestController
@RequestMapping("/bloodSugarUser")
@Api(value = "BloodSugarUserController", tags = {"用户信息管理"})
public class BloodSugarUserController {

    @Value("${FastDFS.url}")
    private String fastDFSUrl;

    @Value("${FastDFS.group}")
    private String group;

    @Autowired
    private BloodSugarBedService bloodSugarBedService;

    @Autowired
    private BloodSugarDoctorService bloodSugarDoctorService;

    @Autowired
    private BloodSugarDepartmentService bloodSugarDepartmentService;

    @Autowired
    private BloodSugarPatientInfoService bloodSugarPatientInfoService;

    @Autowired
    private BloodSugarConcernsUserService bloodSugarConcernsUserService;

    @Autowired
    private BloodSugarGluceService bloodSugarGluceService;

    @Autowired
    private BloodSugarGluceProgramTempService bloodSugarGluceProgramTempService;

    @Autowired
    private BloodSugarGluceProgramService bloodSugarGluceProgramService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private BloodSugarUserService bloodSugarUserService;

    @Autowired
    private FileUtil fileUtil;


    /**
     * APP端新增患者
     *
     * @param bloodSugarPatientInfo 患者详细信息实体
     * @return
     */
    @ApiOperation(value = "APP端新增患者")
    @PostMapping("insertUser")
    @PreAuthorize("hasAnyAuthority('sys:addUser')")
    @Transactional(rollbackFor = Exception.class)
    public Result insertUser(BloodSugarPatientInfo bloodSugarPatientInfo) {
        String username = bloodSugarPatientInfo.getUsername();
        if (StringUtils.isEmpty(username)) {
            return Result.error().code(301).message("请填写用户名");
        }
        String sex = bloodSugarPatientInfo.getSex();
        if (StringUtils.isEmpty(sex)) {
            return Result.error().code(302).message("请选择性别");
        }
        Date brithday = bloodSugarPatientInfo.getBrithday();
        if (brithday == null) {
            return Result.error().code(303).message("请选择生日");
        }
        String phone = bloodSugarPatientInfo.getPhone();
        if (StringUtils.isEmpty(phone)) {
            return Result.error().code(304).message("请填写手机号");
        }
        String patientIcon = bloodSugarPatientInfo.getPatientIcon();
        if (StringUtils.isEmpty(patientIcon)) {
            return Result.error().code(305).message("请选择头像");
        }
        Integer doctorId = bloodSugarPatientInfo.getDoctorId();
        if (doctorId == null || doctorId == 0) {
            return Result.error().code(306).message("请选择医生");
        }
        String sugarType = bloodSugarPatientInfo.getSugarType();
        if (StringUtils.isEmpty(sugarType)) {
            return Result.error().code(307).message("请选择血糖类型");
        }
        Date toHospitalTime = bloodSugarPatientInfo.getToHospitalTime();
        if (toHospitalTime == null) {
            return Result.error().code(308).message("请填写住院时间");
        }
        Integer departmentId = bloodSugarPatientInfo.getDepartmentId();
        if (departmentId == null || departmentId == -1) {
            return Result.error().code(309).message("请选择科室");
        }
        Integer bedId = bloodSugarPatientInfo.getBedId();
        if (bedId == null || bedId == 0) {
            return Result.error().code(310).message("请选择床位");
        }
        Integer deanId = bloodSugarPatientInfo.getDeanId();
        if (deanId == null || deanId == 0) {
            return Result.error().code(311).message("院长Id不能为空");
        }
        String hospitalNum = bloodSugarPatientInfo.getHospitalNum();
        if (StringUtils.isEmpty(hospitalNum)) {
            return Result.error().code(312).message("住院号不能为空");
        }
        QueryWrapper<BloodSugarPatientInfo> query = Wrappers.query();
        query.eq("department_id", departmentId);
        query.eq("bed_id", bedId);
        query.eq("the_hospital_status", '0');
        BloodSugarPatientInfo one = bloodSugarPatientInfoService.getOne(query);
        if (one != null) {
            return Result.error().code(313).message("该床位已被选择，请重新选择");
        }
        QueryWrapper<BloodSugarPatientInfo> phoneQuery = Wrappers.query();
        phoneQuery.eq("phone", phone);
        phoneQuery.eq("the_hospital_status", '0');
        BloodSugarPatientInfo userPhone = bloodSugarPatientInfoService.getOne(phoneQuery);
        if (userPhone != null) {
            return Result.error().code(314).message("手机号已存在");
        }
        QueryWrapper<BloodSugarPatientInfo> query1 = Wrappers.query();
        query1.eq("hospital_num", hospitalNum);
        query1.eq("the_hospital_status", '0');
        BloodSugarPatientInfo two = bloodSugarPatientInfoService.getOne(query1);
        if (two != null) {
            return Result.error().code(315).message("住院号已存在，请重新填写");
        }
        int save = bloodSugarPatientInfoService.insertPatient(bloodSugarPatientInfo);
        List<BloodSugarGluceProgram> bloodSugarGlucePrograms = bloodSugarGluceProgramTempService.bloodSugarGlucePrograms(sugarType);
        if (CollectionUtil.isNotEmpty(bloodSugarGlucePrograms)) {
            bloodSugarGlucePrograms.forEach(bloodSugarGluceProgram -> {
                bloodSugarGluceProgram.setProgramGlUserid(bloodSugarPatientInfo.getId());
            });
        }
        boolean b = bloodSugarGluceProgramService.saveBatch(bloodSugarGlucePrograms);
        if (save > 0 && b ) {
            //修改床位号对应userId
            QueryWrapper<BloodSugarPatientInfo> queryuser1 = Wrappers.query();
            queryuser1.eq("phone", phone);
            queryuser1.eq("hospital_num", hospitalNum);
            BloodSugarPatientInfo userid = bloodSugarPatientInfoService.getOne(queryuser1);
            System.out.println("++++++++++++++++++++++++++++++"+userid.getId());

            UpdateWrapper<BloodSugarBed> queryuserId = Wrappers.update();
            queryuserId.eq("id",bedId);
            queryuserId.set("user_id",userid.getId());
            bloodSugarBedService.update(queryuserId);
            return Result.ok();
        } else {
            return Result.error().code(300).message("新增患者失败");
        }
    }

    /**
     * APP端修改用户信息
     *
     * @param bloodSugarPatientInfo 患者详细信息实体
     * @return
     */
    @ApiOperation(value = "APP端修改患者信息")
    @PostMapping("updateUser")
    @Transactional(rollbackFor = Exception.class)
    public Result updateUser(BloodSugarPatientInfo bloodSugarPatientInfo) {
        Integer id = bloodSugarPatientInfo.getId();
        if (id == null || id == 0) {
            return Result.error().code(299).message("用户id不能为空");
        }
        String username = bloodSugarPatientInfo.getUsername();
        if (StringUtils.isEmpty(username)) {
            return Result.error().code(301).message("请填写用户名");
        }
        String sex = bloodSugarPatientInfo.getSex();
        if (StringUtils.isEmpty(sex)) {
            return Result.error().code(302).message("请选择性别");
        }
        Date brithday = bloodSugarPatientInfo.getBrithday();
        if (brithday == null) {
            return Result.error().code(303).message("请选择生日");
        }
        String phone = bloodSugarPatientInfo.getPhone();
        if (StringUtils.isEmpty(phone)) {
            return Result.error().code(304).message("请填写手机号");
        }
        Integer departmentId = bloodSugarPatientInfo.getDepartmentId();
        if (departmentId == null || departmentId == -1) {
            return Result.error().code(309).message("请重新选择科室");
        }
//        String patientIcon = bloodSugarPatientInfo.getPatientIcon();
//        if (StringUtils.isEmpty(patientIcon)) {
//            return Result.error().code(305).message("请选择头像");
//        }
        Integer doctorId = bloodSugarPatientInfo.getDoctorId();
        if (doctorId == null || doctorId == -1) {
            return Result.error().code(306).message("请选择医生");
        }
        String sugarType = bloodSugarPatientInfo.getSugarType();
        System.out.println("++++++++++++++++++++++++"+sugarType);
        if (StringUtils.isEmpty(sugarType) || "-1".equals(sugarType)) {
            return Result.error().code(307).message("请选择血糖类型");
        }
        Date toHospitalTime = bloodSugarPatientInfo.getToHospitalTime();
        if (toHospitalTime == null) {
            return Result.error().code(308).message("请填写住院时间");
        }

        Integer bedId = bloodSugarPatientInfo.getBedId();
        if (bedId == null || bedId == -1) {
            return Result.error().code(310).message("请选择床位");
        }
        Integer deanId = bloodSugarPatientInfo.getDeanId();
        if (deanId == null || deanId == 0) {
            return Result.error().code(311).message("院长Id不能为空");
        }
        String hospitalNum = bloodSugarPatientInfo.getHospitalNum();
        if (StringUtils.isEmpty(hospitalNum)) {
            return Result.error().code(312).message("住院号不能为空");
        }

        QueryWrapper<BloodSugarPatientInfo> query1 = Wrappers.query();
        query1.eq("hospital_num", hospitalNum);
        query1.eq("the_hospital_status", 0);
        BloodSugarPatientInfo one1 = bloodSugarPatientInfoService.getOne(query1);
        if (one1 != null) {
            if (!one1.getId().equals(id)) {
                return Result.error().code(313).message("住院号已存在");
            }
        }

        QueryWrapper<BloodSugarPatientInfo> query2 = Wrappers.query();
        query2.eq("phone", phone);
        query2.eq("the_hospital_status", 0);
        BloodSugarPatientInfo one2 = bloodSugarPatientInfoService.getOne(query1);
        if (one2 != null) {
            if (!one2.getPhone().equals(phone)) {
                return Result.error().code(314).message("手机号已存在");
            }
        }
        // 判断床位是否被选择，通过床位查询住院用户，如果存在，判断用户id是否一致，一致的话证明没有修改床位，如果不一致，并且用户id不相同，则已被选择
        QueryWrapper<BloodSugarPatientInfo> query3 = Wrappers.query();
        query3.eq("department_id", departmentId);
        query3.eq("bed_id", bedId);
        query3.eq("the_hospital_status", 0);
        BloodSugarPatientInfo one3 = bloodSugarPatientInfoService.getOne(query3);
        if (one3 != null) {
            if (!one3.getBedId().equals(bedId)) {
                return Result.error().code(315).message("该床位已被选择，请重新选择");
            }
        }
        //查找更新前bed表中的床位id
        QueryWrapper<BloodSugarBed> getbed = Wrappers.query();
        getbed.eq("user_id", bloodSugarPatientInfo.getId());
        BloodSugarBed userid = bloodSugarBedService.getOne(getbed);
        //System.out.println("++++++++++++++++++++"+userid.getId());
        //查找
        QueryWrapper<BloodSugarPatientInfo> getconcerns = Wrappers.query();
        getconcerns.eq("id", bloodSugarPatientInfo.getId());
        BloodSugarPatientInfo getconcerns1 = bloodSugarPatientInfoService.getOne(getconcerns);
        //更新
        UpdateWrapper<BloodSugarConcernsUser> concerns = Wrappers.update();
        concerns.eq("doctor_id",getconcerns1.getDoctorId());
        concerns.eq("user_id",bloodSugarPatientInfo.getId());
        concerns.set("doctor_id",doctorId);
        bloodSugarConcernsUserService.update(concerns);

        UpdateWrapper<BloodSugarPatientInfo> updateWrapper = Wrappers.update();
        updateWrapper.eq("id", id);
        updateWrapper.set("dean_id", deanId);
        updateWrapper.set("username", username);
        //updateWrapper.set("patient_icon", patientIcon);
        updateWrapper.set("sex", sex);
        updateWrapper.set("id_card", bloodSugarPatientInfo.getIdCard());
        updateWrapper.set("brithday", brithday);
        updateWrapper.set("phone", phone);
        updateWrapper.set("hospital_num", hospitalNum);
        updateWrapper.set("department_id", departmentId);
        updateWrapper.set("doctor_id", doctorId);
        updateWrapper.set("bed_id", bedId);
        updateWrapper.set("sugar_type", sugarType);
        updateWrapper.set("height", bloodSugarPatientInfo.getHeight());
        updateWrapper.set("weight", bloodSugarPatientInfo.getWeight());
        updateWrapper.set("sugar_num", bloodSugarPatientInfo.getSugarNum());
        boolean update = bloodSugarPatientInfoService.update(updateWrapper);
        //根据更新前bed表中的床位id（修改）上个床位上的患者为0
        UpdateWrapper<BloodSugarBed> deuserId = Wrappers.update();
        deuserId.eq("id",userid.getId());
        deuserId.set("user_id",'0');
        bloodSugarBedService.update(deuserId);
        //更新新的床位
        UpdateWrapper<BloodSugarBed> upuserId = Wrappers.update();
        upuserId.eq("id",bedId);
        upuserId.set("user_id",bloodSugarPatientInfo.getId());
        bloodSugarBedService.update(upuserId);

        if (update) {
            return Result.ok();
        } else {
            return Result.error().code(300).message("修改患者失败");
        }
    }


    @ApiOperation(value = "文件上传")
    @PostMapping("uploadFile")
    public Result uploadFile(MultipartFile file) {
        System.out.println("``````````````````````````````````"+file);
        if (file.isEmpty()) {
            return Result.error().message("文件不能为空").code(301);
        }
        String fileUrl = fileUtil.uploadFile(group, file);
        if (StringUtils.isNotEmpty(fileUrl)) {
            return Result.ok().data(fastDFSUrl + fileUrl);
        } else {
            return Result.error().message("文件上传失败");
        }
    }

    /**
     * App首页数据查询
     *
     * @param userName       姓名
     * @param departmentId   科室id
     * @param gluceType      血糖类型
     * @param toHospitalDate 入院时间
     * @param type           四个Type，1：全部人数   2：异常数据   3：待测人数   4：关注患者
     * @return
     */
    @ApiOperation(value = "App首页数据查询")
    @PostMapping("appHomePage")
//    @PreAuthorize("hasAnyAuthority('sys:homePage')")
    public Result appHomePage(@ApiParam(value = "姓名") @RequestParam(required = false) String userName,
                              @ApiParam(value = "当前登录用户Id") @RequestParam(required = false) String doctorId,
                              @ApiParam(value = "科室id") @RequestParam(required = false) String departmentId, @ApiParam(value = "血糖类型")
                              @RequestParam(required = false) String gluceType, @ApiParam(value = "入院时间") @RequestParam(required = false) String toHospitalDate,
                              @ApiParam(value = "1：全部人数   2：异常数据   3：待测人数   4：关注患者") @RequestParam(required = false, defaultValue = "1") String type,
                              @ApiParam(value = "首页权限id") @RequestParam(required = true) String perId,
                              @ApiParam(name = "current", value = "当前页码") @RequestParam(value = "current", defaultValue = "1", required = false) Integer current,
                              @ApiParam(name = "size", value = "一页显示多少条") @RequestParam(value = "size", defaultValue = "10", required = false) Integer size) throws ParseException {
        if (StringUtils.isEmpty(doctorId)) {
            return Result.error().code(301).message("当前登录医生Id不能为空");
        }
        if (StringUtils.isEmpty(perId)) {
            return Result.error().code(302).message("当前登录医生首页权限不能为空");
        }
        Map<String, Object> map = new HashedMap();
        BloodSugarPatientInfo bloodSugarPatientInfo = new BloodSugarPatientInfo();
        bloodSugarPatientInfo.setDoctorId(Integer.parseInt(doctorId));
        bloodSugarPatientInfo.setPreId(perId);
        //姓名
        if (StringUtils.isNotEmpty(userName)) {
            bloodSugarPatientInfo.setUsername(userName);
        }
        //科室
        if (StringUtils.isNotEmpty(departmentId)&&!"-1".toString().equals(departmentId)&&!"null".equals(departmentId) ) {
            bloodSugarPatientInfo.setDepartmentId(Integer.parseInt(departmentId));
        }
        //血糖
        if (StringUtils.isNotEmpty(gluceType)&&!"-1".toString().equals(gluceType) &&!"null".equals(departmentId)) {
            bloodSugarPatientInfo.setSugarType(gluceType);
        }
        //时间
        if (StringUtils.isNotEmpty(toHospitalDate)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = sdf.parse(toHospitalDate);
            bloodSugarPatientInfo.setToHospitalTime(parse);
        }
        List<AppHomePageUserBean> records = new ArrayList<>();
        // 推算今日未测逻辑
        List<AppHomePageUserBean> unFinishList = new ArrayList<>();
        //全部患者
        List<AppHomePageUserBean> appHomePageUserBeans = bloodSugarPatientInfoService.appHomePageAllPatientInfo(bloodSugarPatientInfo);
        for (AppHomePageUserBean appHomePageUserBean : appHomePageUserBeans) {
            QueryWrapper<BloodSugarGluceProgram> query = Wrappers.query();
            query.eq("program_gl_userid", appHomePageUserBean.getPatientId());
            query.eq("program_gl_option", "1");
            List<BloodSugarGluceProgram> sugarGlucePrograms = bloodSugarGluceProgramService.list(query);
            if (CollectionUtils.isEmpty(sugarGlucePrograms)) {
                unFinishList.add(appHomePageUserBean);
            } else {
                a:
                for (BloodSugarGluceProgram sugarGluceProgram : sugarGlucePrograms) {
                    List<BloodSugarGluce> gluceDataByAttrAndNow = bloodSugarGluceService.getGluceDataByAttrAndNow(sugarGluceProgram.getProgramGlAttr(), appHomePageUserBean.getPatientId().toString());
                    if (CollectionUtils.isEmpty(gluceDataByAttrAndNow)) {
                        unFinishList.add(appHomePageUserBean);
                        break a;
                    }
                }
            }
        }
        switch (type) {
            case "1":
                // 全部患者
                List<AppHomePageUserBean> appHomePageAllPatientInfo = bloodSugarPatientInfoService.appHomePageAllPatientInfo(bloodSugarPatientInfo);
                records.addAll(appHomePageAllPatientInfo);
                break;
            case "2":
                // 异常数据患者
                List<AppHomePageUserBean> abnormalDataByUser = bloodSugarPatientInfoService.abnormalDataByUser(bloodSugarPatientInfo);
                records.addAll(abnormalDataByUser);
                break;
            case "3":
                // 待测人数
                List<AppHomePageUserBean> appHomePageToBeMeasuredInfo = bloodSugarPatientInfoService.appHomePageToBeMeasuredInfo(bloodSugarPatientInfo);
                records.addAll(appHomePageToBeMeasuredInfo);
                break;
            case "4":
                // 关注患者
                List<AppHomePageUserBean> appHomePageConcernsPatientInfo = bloodSugarPatientInfoService.appHomePageConcernsPatientInfo(bloodSugarPatientInfo);
                records.addAll(appHomePageConcernsPatientInfo);
                break;
            default:
                break;
        }
        //给图片添加头访问地址
        if (CollectionUtil.isNotEmpty(records)) {
            records.forEach(user -> {
                user.setPatientIcon(fastDFSUrl + user.getPatientIcon());
            });
        }
        return Result.ok().data(records);
    }

    /**
     * App关注用户
     *
     * @param doctorId 医生id
     * @param userId   用户id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "App关注用户")
    @GetMapping("attentionUser/{doctorId}/{userId}/{type}")
    public Result attentionUser(@ApiParam(value = "用户Id") @PathVariable Integer userId,
                                @ApiParam(value = "医生Id") @PathVariable Integer doctorId,
                                @ApiParam(value = "类型  1:关注  2:取消关注") @PathVariable String type) {
        boolean istrue = false;
        if (type.equals("1")) {
            BloodSugarConcernsUser bloodSugarConcernsUser = new BloodSugarConcernsUser();
            bloodSugarConcernsUser.setDoctorId(doctorId);
            bloodSugarConcernsUser.setUserId(userId);
            bloodSugarConcernsUser.setCreateTime(new Date());
            istrue = bloodSugarConcernsUserService.save(bloodSugarConcernsUser);
        } else {
            QueryWrapper<BloodSugarConcernsUser> deleteQuery = Wrappers.query();
            deleteQuery.eq("doctor_id", doctorId);
            deleteQuery.eq("user_id", userId);
            istrue = bloodSugarConcernsUserService.remove(deleteQuery);
        }
        if (istrue) {
            return Result.ok().message("操作成功");
        } else {
            return Result.error().code(300).message("操作失败");
        }
    }

    /**
     * App查看用户信息
     *
     * @param userId
     * @return
     */
    @ApiOperation(value = "App查看用户信息")
    @PostMapping("getUserInfoByUserId")
    public Result getUserInfoByUserId(String userId) {
        if (StringUtils.isEmpty(userId)) {
            return Result.error().code(301).message("用户Id不能为空");
        }
        QueryWrapper<BloodSugarPatientInfo> query = Wrappers.query();
        query.eq("id", userId);
        BloodSugarPatientInfo one = bloodSugarPatientInfoService.getOne(query);
        if (one != null) {
            //查找科室名字
            QueryWrapper<BloodSugarDepartment> department = Wrappers.query();
            department.eq("id", one.getDepartmentId());
            BloodSugarDepartment department1 = bloodSugarDepartmentService.getOne(department);
            //查找医生名字
            QueryWrapper<BloodSugarDoctor> doctor = Wrappers.query();
            doctor.eq("doctor_id", one.getDoctorId());
            BloodSugarDoctor doctor1 = bloodSugarDoctorService.getOne(doctor);
            //查找床位名字
            QueryWrapper<BloodSugarBed> bed = Wrappers.query();
            bed.eq("id", one.getBedId());
            BloodSugarBed bed1 = bloodSugarBedService.getOne(bed);
            one.setBed_num(bed1.getBedNum()+"");
            one.setPatientIcon(fastDFSUrl + one.getPatientIcon());
            Map<String, Object> map = new HashedMap();
            map.put("data",one);
            map.put("departmentName",department1.getDepartmentName());
            map.put("doctorName",doctor1.getDoctorName());

            System.out.println("department1.getDepartmentName()"+department1.getDepartmentName());
            return Result.ok().data(map);
        } else {
            return Result.error().code(300).message("用户信息不存在");
        }
    }

    /**
     * App修改密码
     *
     * @return
     */
    @ApiOperation(value = "App修改密码")
    @PostMapping("updateUserPwd")
    public Result updateUserPwd(String oldPwd, String newPwd, String twoNewPwd, String account) {
        if (StringUtils.isEmpty(oldPwd)) {
            return Result.error().code(301).message("请填写原密码");
        }
        if (StringUtils.isEmpty(newPwd)) {
            return Result.error().code(302).message("请填写修改后的密码");
        }
        if (StringUtils.isEmpty(twoNewPwd)) {
            return Result.error().code(303).message("请再次填写新密码");
        }
        if (oldPwd.equals(newPwd)) {
            return Result.error().code(306).message("原密码与新密码一致");
        }
        QueryWrapper<BloodSugarUser> queryUser = Wrappers.query();
        queryUser.eq("account", account);
        BloodSugarUser sugarUser = bloodSugarUserService.getOne(queryUser);
        boolean isPwdCorrect = passwordEncoder.matches(oldPwd, sugarUser.getPassword());
        if (!isPwdCorrect) {
            return Result.error().code(304).message("原密码不正确");
        }
        if (!twoNewPwd.equals(newPwd)) {
            return Result.error().code(305).message("请确认密码后再进行提交");
        }
        UpdateWrapper<BloodSugarUser> userUpload = Wrappers.update();
        userUpload.eq("account", account);
        userUpload.set("password", passwordEncoder.encode(twoNewPwd));
        boolean update = bloodSugarUserService.update(userUpload);
        if (update) {
            return Result.ok().message("密码修改成功");
        } else {
            return Result.error().message("密码修改失败");
        }
    }


    @ApiOperation(value = "APP血糖测量跳转用户信息")
    @PostMapping("getPatientIntoByType")
    public Result getPatientIntoByType(@ApiParam(value = "条形码") @RequestParam(required = false) String barCode, @ApiParam(value = "住院号")
    @RequestParam(required = false) String toHospitalNum, @ApiParam(value = "床位号") @RequestParam(required = false) String bedNum, @ApiParam(value = "电话")
                                       @RequestParam(required = false) String phone, @ApiParam(value = "科室，床位号不为空时，科室ID必传") @RequestParam(required = false) String departmentId,
                                       @ApiParam(value = "医生ID") @RequestParam(required = false) String doctorId) {
        if (StringUtils.isEmpty(barCode) && StringUtils.isEmpty(toHospitalNum) && StringUtils.isEmpty(bedNum) && StringUtils.isEmpty(phone)) {
            return Result.error().code(301).message("至少选择一种方式查看用户");
        }
        if (!StringUtils.isEmpty(bedNum)) {
            if (StringUtils.isEmpty(departmentId)) {
                return Result.error().code(302).message("床位号方式查看用户，请选择科室信息");
            }
        }
        if (StringUtils.isNotEmpty(barCode)) {
            toHospitalNum = barCode;
        }
        BloodSugarPatientInfo bloodSugarPatientInfo = bloodSugarPatientInfoService.getBloodSugarPatientInfoByType(toHospitalNum, phone, bedNum, departmentId,doctorId);
        if (bloodSugarPatientInfo != null) {
            bloodSugarPatientInfo.setPatientIcon(fastDFSUrl + bloodSugarPatientInfo.getPatientIcon());
            return Result.ok().data(bloodSugarPatientInfo);
        } else {
            return Result.error().code(300).message("请输入正确信息");
        }
    }
}